package zy.vo.shop;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zy.entity.base.product.T_Base_Product;
import zy.entity.base.size.T_Base_Size;
import zy.entity.base.size.T_Base_SizeList;
import zy.entity.shop.gift.T_Shop_GiftList;
import zy.entity.shop.gift.T_Shop_Gift_Product;
import zy.entity.shop.gift.T_Shop_SizeCommon;
import zy.entity.sys.user.T_Sys_User;
import zy.util.StringUtil;
import zy.vo.common.SizeHorizontalVO;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class GiftVO {
	public static String getJsonAddProductInfo(
			T_Base_Product product
			,List<T_Shop_Gift_Product> braColors
			,List<T_Base_Size> sizes
			,List<T_Shop_Gift_Product> inputs
			,List<T_Shop_Gift_Product> stockAmounts
			,Map<String,Object> usableStockMap
			,T_Sys_User user){
		try {
			StringBuffer jsonProduct=new StringBuffer();
			jsonProduct.append("{\"no\":\""+product.getPd_code()+"\",");
			jsonProduct.append("\"name\":\""+product.getPd_name()+"\",");
			jsonProduct.append("\"bd_name\":\""+product.getPd_bd_name()+"\",");
			jsonProduct.append("\"tp_name\":\""+product.getPd_tp_name()+"\",");
			jsonProduct.append("\"season\":\""+product.getPd_season()+"\",");
			jsonProduct.append("\"year\":\""+product.getPd_year()+"\",");
			jsonProduct.append("\"sell_priceShow\":\""+product.getPd_sell_price()+"\",");
			jsonProduct.append("\"sell_price\":\""+product.getPd_sell_price()+"\",");
			jsonProduct.append("\"sort_priceShow\":\""+product.getPd_sort_price()+"\",");
			jsonProduct.append("\"sort_price\":\""+product.getPd_sort_price()+"\",");
			jsonProduct.append("\"cost_price\":\""+product.getPd_cost_price()+"\",");
			jsonProduct.append("\"szg_code\":\""+product.getPd_szg_code()+"\",");
			jsonProduct.append("\"unit_name\":\""+product.getPd_unit()+"\",");
			jsonProduct.append("\"img_path\":\""+StringUtil.trimString(product.getPdm_img_path())+"\"}");
			
			StringBuffer jsonSizes=new StringBuffer();
			jsonSizes.append("\"sizes\":[");
			for (T_Base_Size size : sizes) {
				jsonSizes.append("{\"code\":\""+size.getSz_code()+"\",");
				jsonSizes.append("\"name\":\""+size.getSz_name()+"\"},");
			}
			if (sizes!=null&&sizes.size()>0){
				jsonSizes.deleteCharAt(jsonSizes.length()-1);
			}
			jsonSizes.append("]");
			
			StringBuffer jsonList=new StringBuffer();
			jsonList.append("\"rows\":[");
			int rowIndex=1;
			
			for (T_Shop_Gift_Product braColor : braColors) {
				jsonList.append("{\"id\":\""+rowIndex+"\",");rowIndex++;
				jsonList.append("\"cr_name\":\""+braColor.getCr_name()+"\",");
				jsonList.append("\"cr_code\":\""+braColor.getCr_code()+"\",");
				jsonList.append("\"br_name\":\""+braColor.getBr_name()+"\",");
				jsonList.append("\"br_code\":\""+braColor.getBr_code()+"\",");
				int amountInput=0,amountStock=0;
				int amountGet = 0;
				for (T_Base_Size size : sizes) {
					for (int i = 0; i <stockAmounts.size(); i++) {
						T_Shop_Gift_Product stock=stockAmounts.get(i);
						if (
								braColor.getCr_code().equals(stock.getCr_code())
								&&size.getSz_code().equals(stock.getSz_code())
								&&braColor.getBr_code().equals(stock.getBr_code())
								){
							amountStock= stock.getTotalamount();
							stockAmounts.remove(stock);
							break;
						}
					}
					
					for (int i = 0; i <inputs.size(); i++) {
						T_Shop_Gift_Product input=inputs.get(i);
						if (braColor.getCr_code().equals(input.getCr_code())
								&&size.getSz_code().equals(input.getSz_code())
								&&braColor.getBr_code().equals(input.getBr_code())){
							amountInput= input.getTotalamount();
							amountGet = input.getGetamount();
							inputs.remove(input);
							break;
						}
					}
					
					//商品编号+颜色+尺码+杯型
					String sub_code=StringUtil.trimString(product.getPd_code())
								+StringUtil.trimString(braColor.getCr_code())
								+StringUtil.trimString(size.getSz_code())
								+StringUtil.trimString(braColor.getBr_code());
					if (usableStockMap != null){//启用可用库存
						Object obj=usableStockMap.get(sub_code);
						int usableStockAmount =0;
						if (obj!=null){
							usableStockAmount = (int)((double)(Double)obj);
						}
						if (amountInput!=0||usableStockAmount!=0||amountStock!=0){
							jsonList.append("\""+size.getSz_code()+"\":");
							jsonList.append("\""+amountStock
									+"/"+(amountStock+usableStockAmount)//库存+在途库存
									+"/"+(amountInput==0?"":amountInput)+"\",");
						}
					}else{
						if (amountInput!=0||amountStock!=0){
							jsonList.append("\""+size.getSz_code()+"\":");
							jsonList.append("\""+amountStock
									+"/"+(amountInput==0?"":amountInput)+"\",");
						}
					}
					//已领取数量
					jsonList.append("\""+size.getSz_code()+"_get"+"\":");
					jsonList.append("\""+amountGet+"\",");
					amountInput=0;amountStock=0;amountGet=0;
				}
				jsonList.deleteCharAt(jsonList.length()-1);
				jsonList.append("},");	
			}
			jsonList.deleteCharAt(jsonList.length()-1);
			jsonList.append("]");
			
			StringBuffer jsonData=new StringBuffer();
			jsonData.append("{\"product\":"+jsonProduct+","+jsonSizes.toString()+",\"data\":{"+jsonList.toString()+"}}");
			return jsonData.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "{}";
		}
	}
	public static String getJsonAddProductInfoForModify(
			T_Base_Product product
			,List<T_Shop_Gift_Product> braColors
			,List<T_Base_Size> sizes
			,List<T_Shop_Gift_Product> inputs
			,List<T_Shop_Gift_Product> stockAmounts
			,Map<String,Object> usableStockMap
			,T_Sys_User user){
		try {
			StringBuffer jsonProduct=new StringBuffer();
			jsonProduct.append("{\"no\":\""+product.getPd_code()+"\",");
			jsonProduct.append("\"name\":\""+product.getPd_name()+"\",");
			jsonProduct.append("\"bd_name\":\""+product.getPd_bd_name()+"\",");
			jsonProduct.append("\"tp_name\":\""+product.getPd_tp_name()+"\",");
			jsonProduct.append("\"season\":\""+product.getPd_season()+"\",");
			jsonProduct.append("\"year\":\""+product.getPd_year()+"\",");
			jsonProduct.append("\"sell_priceShow\":\""+product.getPd_sell_price()+"\",");
			jsonProduct.append("\"sell_price\":\""+product.getPd_sell_price()+"\",");
			jsonProduct.append("\"sort_priceShow\":\""+product.getPd_sort_price()+"\",");
			jsonProduct.append("\"sort_price\":\""+product.getPd_sort_price()+"\",");
			jsonProduct.append("\"cost_price\":\""+product.getPd_cost_price()+"\",");
			jsonProduct.append("\"szg_code\":\""+product.getPd_szg_code()+"\",");
			jsonProduct.append("\"unit_name\":\""+product.getPd_unit()+"\",");
			jsonProduct.append("\"img_path\":\""+StringUtil.trimString(product.getPdm_img_path())+"\"}");
			
			StringBuffer jsonSizes=new StringBuffer();
			jsonSizes.append("\"sizes\":[");
			for (T_Base_Size size : sizes) {
				jsonSizes.append("{\"code\":\""+size.getSz_code()+"\",");
				jsonSizes.append("\"name\":\""+size.getSz_name()+"\"},");
			}
			if (sizes!=null&&sizes.size()>0){
				jsonSizes.deleteCharAt(jsonSizes.length()-1);
			}
			jsonSizes.append("]");
			
			StringBuffer jsonList=new StringBuffer();
			jsonList.append("\"rows\":[");
			int rowIndex=1;
			
			for (T_Shop_Gift_Product braColor : braColors) {
				jsonList.append("{\"id\":\""+rowIndex+"\",");rowIndex++;
				jsonList.append("\"cr_name\":\""+braColor.getCr_name()+"\",");
				jsonList.append("\"cr_code\":\""+braColor.getCr_code()+"\",");
				jsonList.append("\"br_name\":\""+braColor.getBr_name()+"\",");
				jsonList.append("\"br_code\":\""+braColor.getBr_code()+"\",");
				int amountInput=0,amountStock=0;
				int amountPub = 0;
				int amountGet = 0;
				for (T_Base_Size size : sizes) {
					for (int i = 0; i <stockAmounts.size(); i++) {
						T_Shop_Gift_Product stock=stockAmounts.get(i);
						if (
								braColor.getCr_code().equals(stock.getCr_code())
								&&size.getSz_code().equals(stock.getSz_code())
								&&braColor.getBr_code().equals(stock.getBr_code())
								){
							amountStock= stock.getTotalamount();
							stockAmounts.remove(stock);
							break;
						}
					}
					for (int i = 0; i <inputs.size(); i++) {
						T_Shop_Gift_Product input=inputs.get(i);
						if (braColor.getCr_code().equals(input.getCr_code())
								&&size.getSz_code().equals(input.getSz_code())
								&&braColor.getBr_code().equals(input.getBr_code())
								){
							amountInput= input.getAddamount();
							amountPub = input.getTotalamount();
							amountGet = input.getGetamount();
							inputs.remove(input);
							break;
						}
					}
					
					//货号+颜色+尺码+杯型
					String sub_code=StringUtil.trimString(product.getPd_code())
							+StringUtil.trimString(braColor.getCr_code())
							+StringUtil.trimString(size.getSz_code())
							+StringUtil.trimString(braColor.getBr_code());
					if (usableStockMap != null){//启用可用库存
						Object obj=usableStockMap.get(sub_code);
						int usableStockAmount =0;
						if (obj!=null){
							usableStockAmount = (int)((double)(Double)obj);
						}
						if (amountInput!=0||usableStockAmount!=0||amountStock!=0){
							jsonList.append("\""+size.getSz_code()+"\":");
							jsonList.append("\""+amountStock
									+"/"+(amountStock+usableStockAmount)//库存+在途库存
									+"/"+(amountInput==0?"":amountInput)+"\",");
						}
					}else{
						if (amountInput!=0||amountStock!=0){
							jsonList.append("\""+size.getSz_code()+"\":");
							jsonList.append("\""+amountStock
									+"/"+(amountInput==0?"":amountInput)+"\",");
						}
					}
					//已发布数量
					jsonList.append("\""+size.getSz_code()+"_pub"+"\":");
					jsonList.append("\""+amountPub+"\",");
					//已领取数量
					jsonList.append("\""+size.getSz_code()+"_get"+"\":");
					jsonList.append("\""+amountGet+"\",");
					amountInput=0;amountStock=0;amountGet=0;amountPub=0;
				}
				jsonList.deleteCharAt(jsonList.length()-1);
				jsonList.append("},");	
			}
			jsonList.deleteCharAt(jsonList.length()-1);
			jsonList.append("]");
			
			StringBuffer jsonData=new StringBuffer();
			jsonData.append("{\"product\":"+jsonProduct+","+jsonSizes.toString()+",\"data\":{"+jsonList.toString()+"}}");
			return jsonData.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "{}";
		}
	}
	
	public static List<T_Shop_GiftList> convertJsonToGiftListTemp(String jsonStr,T_Sys_User user){
		List<T_Shop_GiftList> list =new ArrayList<T_Shop_GiftList>();
		T_Shop_GiftList model;
		JSONArray jsonArray=JSONArray.parseArray(jsonStr);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			model=new T_Shop_GiftList();
			model.setGil_pd_code(StringUtil.trimString(jsonObject.getString("no")));
			model.setGil_cr_code(StringUtil.trimString(jsonObject.getString("cr_code")));
			model.setGil_bs_code(StringUtil.trimString(jsonObject.getString("br_code")));
			/*if ("".equals(model.getLGLT_BS_Code())){
				model.setLGLT_BS_ISBras("0");
			}else{
				model.setLGLT_BS_ISBras("1");
			}*/
			model.setGil_sz_code(StringUtil.trimString(jsonObject.getString("sz_code")));
			model.setGil_szg_code(StringUtil.trimString(jsonObject.getString("szg_code")));
			/*model.setLGLT_CU_Name(StringUtil.trimString(jsonObject.getString("cuName")));*/
			model.setGil_sub_code(model.getGil_pd_code()+model.getGil_cr_code()+model.getGil_sz_code()+model.getGil_bs_code());
			model.setCompanyid(user.getCompanyid());
			model.setGil_user_code(user.getUs_code());
			model.setGil_totalamount(jsonObject.getInteger("amount"));
			/*model.setLGLT_RetailPrice(Double.parseDouble(jsonObject.getString("unitPrice")));
			model.setLGLT_RetailMoney(model.getLGLT_Amount()*model.getLGLT_RetailPrice());*/
			model.setOperateType(jsonObject.getString("operateType"));
			list.add(model);
		}
		return list;
	}
	
	public static List<T_Shop_GiftList> convertJsonToGiftListTempForModify(String jsonStr,T_Sys_User user){
		List<T_Shop_GiftList> list =new ArrayList<T_Shop_GiftList>();
		T_Shop_GiftList model;
		JSONArray jsonArray=JSONArray.parseArray(jsonStr);
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			model=new T_Shop_GiftList();
			model.setGil_pd_code(StringUtil.trimString(jsonObject.getString("no")));
			model.setGil_cr_code(StringUtil.trimString(jsonObject.getString("cr_code")));
			model.setGil_bs_code(StringUtil.trimString(jsonObject.getString("br_code")));
			/*if ("".equals(model.getLGLT_BS_Code())){
				model.setLGLT_BS_ISBras("0");
			}else{
				model.setLGLT_BS_ISBras("1");
			}*/
			model.setGil_sz_code(StringUtil.trimString(jsonObject.getString("sz_code")));
			model.setGil_szg_code(StringUtil.trimString(jsonObject.getString("szg_code")));
			/*model.setLGLT_CU_Name(StringUtil.trimString(jsonObject.getString("cuName")));*/
			model.setGil_sub_code(model.getGil_pd_code()+model.getGil_cr_code()+model.getGil_sz_code()+model.getGil_bs_code());
			model.setCompanyid(user.getCompanyid());
			model.setGil_user_code(user.getUs_code());
			model.setGil_addamount(jsonObject.getInteger("amount"));
			model.setGil_totalamount(jsonObject.getInteger("pubAmount"));
			/*model.setLGLT_RetailPrice(Double.parseDouble(jsonObject.getString("unitPrice")));
			model.setLGLT_RetailMoney(model.getLGLT_Amount()*model.getLGLT_RetailPrice());*/
			model.setOperateType(jsonObject.getString("operateType"));
			list.add(model);
		}
		return list;
	}
	
	public static Map<String, Object> getJsonSizeData_Gift(List<T_Base_SizeList> sizeGroupList,List<T_Shop_GiftList> dataList){
		if (sizeGroupList != null && sizeGroupList.size() > 0) {
			int[] maxColNumArray = new int[1];
            Map<String, List<String>> map = new HashMap<String, List<String>>();
            List<List<String>> lstRes = SizeHorizontalVO.getSizeModeTitleInfoList(map, maxColNumArray, sizeGroupList);
            List<T_Shop_SizeCommon> list = getSizeModeList_Order(dataList,maxColNumArray[0],map);
            int sizeMaxSize = maxColNumArray[0];
			int[] totalSizeBySingle = new int[sizeMaxSize];
			Collections.sort(lstRes, new Comparator<List<String>>() {
				@Override
				public int compare(List<String> o1, List<String> o2) {
					return o1.size() > o2.size() ? -1 : 0;
				}
			});
			int Amount_Total = 0;
			HashMap<String, Object> sizeGroupMap = new HashMap<String, Object>();
			List<Map<String, Object>> values = new ArrayList<Map<String, Object>>();
			HashMap<String, Object> entry = null;
			if (list == null || list.isEmpty()) {
			} else {
				for (T_Shop_SizeCommon item : list) {
					entry = new HashMap<String, Object>();
					entry.put("id", item.getId());
					entry.put("pd_code", item.getPd_code());
					entry.put("pd_no", item.getPd_no());
					entry.put("pd_name", item.getPd_name());
					entry.put("pd_unit", item.getPd_unit());
					entry.put("cr_code", item.getCr_code());
					entry.put("cr_name", item.getCr_name());
					entry.put("br_code", item.getBr_code());
					entry.put("br_name", item.getBr_name());
					int[] amounts = item.getSingle_amount();
					if (lstRes == null || lstRes.size() <= 0) {
					} else {
						String[] header = null;
						int amountSize = 0;
						if (map.containsKey(item.getSzg_code())) {
							amountSize = map.get(item.getSzg_code()).size();
						}
						List<String> headers = lstRes.get(0);
						for (int i = 0; i < headers.size(); i++) {
							header = headers.get(i).split("_AND_");
							if (i >= amountSize) {
								entry.put(header[0], "");
							} else {
								entry.put(header[0],amounts[i] == 0 ? "": amounts[i] + "");
								totalSizeBySingle[i] = totalSizeBySingle[i] + amounts[i];
							}
						}
					}
					entry.put("Amount_Total", item.getTotalamount());
					entry.put("sizeGroupCode", item.getSzg_code());
					Amount_Total += item.getTotalamount();
					values.add(entry);
				}
			}
			if (lstRes == null || lstRes.size() <= 0) {
			} else {
				String[] header = null;
                List<String> headers = lstRes.get(0);
                for (int i = 0; i < headers.size(); i++) {
                    header = headers.get(i).split("_AND_");
                    sizeGroupMap.put(header[0], totalSizeBySingle[i] == 0 ? "" : totalSizeBySingle[i]);
                }
			}
			HashMap<String, Object> userData = new HashMap<String, Object>();
			userData.put("pd_no", "合计：");
			userData.put("Amount_Total", Amount_Total);
			userData.putAll(sizeGroupMap);
			
			Map<String, Object> resultMap = new HashMap<String, Object>();
			resultMap.put("data", values);
			resultMap.put("userData", userData);
			return resultMap;
		}
		return null;
	}
	
	private static List<T_Shop_SizeCommon> getSizeModeList_Order(List<T_Shop_GiftList> list,int maxColNumArray, Map<String, List<String>> map) {
		// 尺码横排结果
		List<T_Shop_SizeCommon> lstRes = new ArrayList<T_Shop_SizeCommon>();
		int[] subArray = null;
		T_Shop_SizeCommon temp = null;
		int Amount_Total = 0;
		String pd_code = "";
		String cr_code = "";
		String br_code = "";
		List<String> sizeListWithSzgIdList = null;
		for (T_Shop_GiftList item : list) {
			if (!pd_code.equals(item.getGil_pd_code())
					|| !cr_code.equals(item.getGil_cr_code())
					|| !br_code.equals(item.getGil_bs_code())
					) {
				pd_code = StringUtil.trimString(item.getGil_pd_code());
				cr_code = StringUtil.trimString(item.getGil_cr_code());
				br_code = StringUtil.trimString(item.getGil_bs_code());
				Amount_Total = 0;
				temp = new T_Shop_SizeCommon();
				subArray = new int[maxColNumArray];
				temp.setSingle_amount(subArray);
				lstRes.add(temp);
			}
			temp.setId(item.getGil_id());
			temp.setPd_code(item.getGil_pd_code());
			temp.setPd_no(item.getPd_no());
			temp.setPd_name(item.getPd_name());
			temp.setPd_unit(item.getPd_unit());
			temp.setSzg_code(item.getGil_szg_code());
			temp.setCr_code(item.getGil_cr_code());
			temp.setCr_name(item.getCr_name());
			temp.setBr_code(item.getGil_bs_code());
			temp.setBr_name(item.getBr_name());
			Amount_Total += item.getGil_totalamount();
			temp.setTotalamount(Amount_Total);
			
			//获得尺码组编号对应的尺码编号信息
			sizeListWithSzgIdList = (List<String>)map.get(item.getGil_szg_code());
			//然后根据对应的下标确定其位置
			int szIdIndex = sizeListWithSzgIdList.indexOf(item.getGil_sz_code());
			//根据下标位置得到，其对应的尺码数量，然后进行累加
			subArray[szIdIndex] += item.getGil_totalamount();
		}
		return lstRes;
	}
}
